<?php

namespace App\Http\Controllers\Admin;

use Auth;
use JWTAuth;
use Exception;
use App\Models\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Login\LoginRequest;
use App\Http\Requests\Admin\Login\ResetPassword;
use App\Package\Message\Message;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;

/**
 * 处理用户登录逻辑控制器
 *
 * Date: 2018/04/26
 * @author Tenny
 * @package App\Http\Controllers\Auth
 */
class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 处理用户登录逻辑
     *
     * Date: 2018/04/26
     * @author Tenny
     * @param LoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(LoginRequest $request)
    {
        // 验证用户输入凭证
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/'],
            'password' => 'required|string|min:6|max:18',
        ], [
            'phone.required' => '请输入手机号',
            'phone.regex' => '请输入正确的手机号',
            'password.required' => '请输入密码',
            'password.string' => '请输入正确格式的密码',
            'password.min' => '密码不得少于:min个字符',
            'password.max' => '密码不得超过:max个字符',
        ]);

        // 获取凭证
        $credentials = [
            $this->username() => $request->get('phone'),
            'password' => $request->get('password')
        ];
        // 判断是否是管理员账户登录
        try {
            if (!$token = $this->guard('admin')->attempt($credentials)) {
                return failed('认证失败，用户名或密码不正确', 401);
            }
        } catch (JWTException $exception) {
            return internalError();
        }
        $user = Admin::query()->where('phone', $request->get('phone'))->first();
        return success([
            'id' => $user->id,
            'name' => $user->name,
            'phone' => $user->phone,
            'gender' => $user->gender,
            'avatar' => $user->avatar,
            'service_id' => 0,
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => config('jwt.ttl') * 60
        ]);
    }

    /**
     * 处理用户注销逻辑
     *
     * Date: 2018/04/26
     * @author Tenny
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        try {
            $this->guard()->logout();
        } catch (Exception $exception) {
            return internalError();
        }
        return respond([], '注销成功');
    }

    /**
     * 重置密码
     *
     * Date: 2018/06/01
     * @author Tenny
     * @param ResetPassword $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function password(ResetPassword $request)
    {
        $params = $this->validate($request, [
            'old_password' => 'required',
            'new_password' => 'required',
        ], [
            'old_password.required' => '请输入旧密码',
            'new_password.required' => '请输入新密码',
        ]);
        $user = Auth::guard('admin')->user();
        $result = Hash::check($params['old_password'], $user->getAuthPassword());
        if ($result) {
            $user->password = $params['new_password'];
            $res = $user->saveOrFail();
            if ($res) {
                return updated([], '您的密码修改成功');
            } else {
                return failed('修改密码失败！');
            }
        }
        return failed('您输入的旧密码有误，修改密码失败！');
    }

    /**
     * 定义用于验证的用户的字段
     *
     * Date: 2018/06/01
     * @author Tenny
     * @return string
     */
    public function username()
    {
        return 'phone';
    }

    /**
     * 定义默认的Guard
     *
     * Date: 2018/06/01
     * @author Tenny
     * @param $guard
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
     */
    public function guard($guard = 'admin')
    {
        return Auth::guard($guard);
    }
}
